// import Footer from '@/components/Footer';
import { Question, SelectLang } from '@/components/RightContent';
import { LinkOutlined } from '@ant-design/icons';
import { Settings as LayoutSettings, intlMap } from '@ant-design/pro-components';
import { SettingDrawer } from '@ant-design/pro-components';
import { RunTimeLayoutConfig } from '@umijs/max';
import { history, Link, useIntl } from '@umijs/max';
import defaultSettings from '../config/defaultSettings';
import { errorConfig } from './requestErrorConfig';
import { currentUser as queryCurrentUser } from './services/ant-design-pro/api';
import React from 'react';
import { AvatarDropdown, AvatarName } from './components/RightContent/AvatarDropdown';
import HeaderNav from './components/HeaderNav';
import Breadcrumb from './components/Breadcrumb'
const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';


/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState() {
  const fetchUserInfo = async () => {
    try {
      const msg = await queryCurrentUser({
        skipErrorHandler: true,
      });
      return msg.data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  // 如果不是登录页面，执行
  const { location } = history;
  if (location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: defaultSettings,
    };
  }
  return {
    fetchUserInfo,
    settings: defaultSettings,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout = ({ initialState, setInitialState }) => {
  const { location } = history;
  const intl = useIntl()
  let bread = []
  localStorage.pathname = location.pathname;
  let data = [];
  if (location.pathname.includes('/supplierportal')) {
    data.push({
      path: '/supplierportal',
      name: '供应商门户',
      headerTitleRender: true,    // title:'bbb',
      // 隐藏自己和子菜单
      // hideInMenu: true,
      flatMenu: true,
      // menuHeaderRender: false,
      routes: [{
        path: '/supplierportal',
        redirect: '/supplierportal/supplierorganization',
      },
      {
        path: '/supplierportal/supplierorganization',
        name: '供应商组织',
        routes: [{
          path: '/supplierportal/supplierorganization',
          redirect: '/supplierportal/supplierorganization/personnelmanagement',
        },
        {
          path: '/supplierportal/supplierorganization/personnelmanagement',
          name: intl.formatMessage({
            id: 'TEXT_17',
            defaultMessage:'123'
          }
          ),
          component: './SupplierPortal/SupplierOrganization/PersonnelManagement'
        },
        {
          path: '/supplierportal/supplierorganization/roles',
          name: '角色管理',
          component: './SupplierPortal/SupplierOrganization/Roles'
        },
        ]
      },
      // {
      //   path: '/supplierportal/parametersettings',
      //   name: '参数设置',
      //   routes: [{
      //     path: '/supplierportal/parametersettings',
      //     redirect: '/supplierportal/parametersettings/basicparameters',
      //   },
      //   {
      //     path: '/supplierportal/parametersettings/basicparameters',
      //     name: '基础参数',
      //     component: './SupplierPortal/ParameterSettings/BasicParameters'
      //   },
      //   {
      //     path: '/supplierportal/parametersettings/mailserve',
      //     name: '邮件服务',
      //     component: './SupplierPortal/ParameterSettings/MailServe'
      //   },
      //   ]
      // },
      {
        path: '/supplierportal/tenantmanagement',
        name: '租户管理',
        component: './SupplierPortal/TenantManagement'
      },
      {
        path: '/supplierportal/projectmanagement',
        name: '项目管理',
        component: './SupplierPortal/ProjectManagement'
      },

      ],
    },)

  } else if (location.pathname.includes('/tenantportal')) {
    data.push({
      path: '/tenantportal',
      name: '供应商门户',
      headerTitleRender: true,
      flatMenu: true,
      routes: [{
        path: '/tenantportal',
        redirect: '/tenantportal/tenantmanagement',
      },
      {
        path: '/tenantportal/tenantmanagement',
        name: '供应商组织',
        component: './TenantPortal/TenantManagement'

      },

      ],
    },)
  } else {
    data.push({
      path: '/home',
      name: '个人门户',
      component: './Home',
      menuRender: false, // 不展示菜单
      menuHeaderRender: false, // 不展示菜单顶栏
      hideInMenu: true,
    },)
  }
  // return <div>mmm</div>
  return {
    //配置动态路由
    menu: {
      // 每当 initialState?.currentUser?.userid 发生修改时重新执行 request
      params: {
        pathname: localStorage.pathname,
      },
      request: async (params, defaultMenuData) => {
        // initialState.currentUser 中包含了所有用户信息
        const menuData = data;
        return menuData;
      },
    },
    // 侧边栏的配置
    collapsed: false,
    collapse: false,
    ErrorBoundary: false,
    breakpoint: false,
    // 侧边栏点击获取元素信息，配置面包屑
    breadcrumbRender: (router) => {
      console.log(router);
      bread.push(...router)
      localStorage.bread = JSON.stringify(router)
    },
    // 侧边栏最上方的渲染
    menuExtraRender: () => {
      return <div style={{ marginBottom: 16 }}>{localStorage.nav}</div>
    },
    // header部分center部分的组件渲染
    headerContentRender: () => {
      return <HeaderNav />
    },
    // header的right部分（包括用户头像，国际化）
    actionsRender: () => [<Question key="doc" />, <SelectLang key="SelectLang" />],
    avatarProps: {
      src: initialState?.currentUser?.avatar,
      title: <AvatarName />,
      render: (_, avatarChildren) => {
        return <AvatarDropdown>{avatarChildren}</AvatarDropdown>;
      },
    },
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    // footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },

    links: isDev
      ? [
        <Link key="openapi" to="/umi/plugin/openapi" target="_blank">
          <LinkOutlined />
          <span>OpenAPI 文档</span>
        </Link>,
      ]
      : [],
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        // article内容区域的渲染
        <>
        {
         location.pathname=='/home'?(<></>): <Breadcrumb />
        }
          {
            children}
          <SettingDrawer
            disableUrlParams
            breadcrumbRender={(router) => {
              console.log(router);
            }}
            enableDarkTheme
            settings={initialState?.settings}
            onSettingChange={(settings) => {
              setInitialState((preInitialState) => ({
                ...preInitialState,
                settings,
              }));
            }}
          />
        </>
      );
    },
    ...initialState?.settings,
  };
};

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request = {
  ...errorConfig,
};
